//
//  NetworkManager.m
//  MIHelloNetwork101
//
//  Created by on 13-1-21.
//  Copyright (c) . All rights reserved.
//

#import "NetworkManager.h"
#import "DownloadCarObj.h"
#import "SHA1.h"

#define NetworkManager_LowLevel_MaxTaskCount 4
#define NetworkManager_MiddleLevel_MaxTaskCount 2

static NetworkManager *instance;

@interface NetworkManager ()
@property (nonatomic, readonly) NSString* tempCarsPath;
@property (nonatomic, readonly) DownloadObjectType  downloadObjType;
@end

@implementation NetworkManager
@synthesize tempCarsPath    =   _tempCarsPath;
@synthesize downloadObjType =   _downloadObjType;

+ (NetworkManager*)getInstance{
    @synchronized(self){
        if (!instance) {
            instance = [NetworkManager new];
        }
    }
    
    return instance;
}

- (id)init{
    self = [super init];
    if (self) {
//       self.host = @"172.18.3.69";
        self.host = [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"];
        taskArray = [NSMutableArray new];
        
        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        _tempCarsPath = [[NSString stringWithFormat:@"%@/TempCars",[paths objectAtIndex:0]] copy];
        
        iLowLevelNetworkQueue = [ASINetworkQueue new];
        iLowLevelNetworkQueue.maxConcurrentOperationCount = NetworkManager_LowLevel_MaxTaskCount;
        iLowLevelNetworkQueue.shouldCancelAllRequestsOnFailure = NO;
        iLowLevelNetworkQueue.showAccurateProgress = YES;// 是否允许通知进度
        [iLowLevelNetworkQueue go];
        
        iMiddleLevelNetworkQueue = [ASINetworkQueue new];
        iMiddleLevelNetworkQueue.maxConcurrentOperationCount = NetworkManager_MiddleLevel_MaxTaskCount;
        iMiddleLevelNetworkQueue.shouldCancelAllRequestsOnFailure = NO;
        iMiddleLevelNetworkQueue.showAccurateProgress = YES;
        [iMiddleLevelNetworkQueue go];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decompressComplete:) name:Decompress_Complete object:nil];
    }
    
    return self;
}

//
- (BOOL)startTaskAsync:(NetworkTask*)task{
    return [self startTaskAsync:task level:NetworkManagerTaskLevel_NotBlocking];
}

- (BOOL)startTaskAsync:(NetworkTask*)task level:(NetworkManagerTaskLevel)level{
        [self addNotificationWithTask:task];
        [taskArray addObject:task];
        switch (level) {
            case NetworkManagerTaskLevel_Low:{
                [iLowLevelNetworkQueue addOperation:task.request];
                break;
            }
            case NetworkManagerTaskLevel_Middle:{
                [iMiddleLevelNetworkQueue addOperation:task.request];
                break;
            }
            case NetworkManagerTaskLevel_NotBlocking:{
                [task.request startAsynchronous];
                break;
            }   
            default:
                break;
        }
        
        return YES;
}

//取消任务
- (void)cancelTaskByIndentifier:(NSString*)taskIndentifier {
    if ([NSString validString:taskIndentifier]) {
        for (NetworkTask* task in taskArray) {
            if ([task.indentifier isEqualToString:taskIndentifier]) {
                if (task.request) {
                    task.request.delegate = nil;
                    [task.request cancel];
                }
                [taskArray removeObject:task];
                break;
            }
        }
    }
}

//根据URL得到DownLoadObject，这个DownLoadObject可能是已经下载了一部分的对象
-(DownloadCarObj *)GetDownLoadObjectWithName:(NSString*)fileName URL:(NSString *)urlstring
{
    //modify by xiaolong for add video resource download
//    BOOL isCarInfo = YES;
//    if (NSNotFound != [urlstring rangeOfString:@"company"].location) {
//        isCarInfo = NO;
//    }
    _downloadObjType = IsCarInfo;//车种资源
    if (![fileName hasSuffix:@".zip"]) {
        _downloadObjType = IsVideo;//视频资源
    } else if (NSNotFound != [fileName rangeOfString:@"company"].location) {
        _downloadObjType = IsCompany;//走进广本和本田科技资源
    }
    //end modify
    
    NSString * sha1string = sha1([urlstring UTF8String]);
    if (IsVideo == _downloadObjType) {
        sha1string = [[fileName componentsSeparatedByString:@"."] objectAtIndex:0];
    }
    DownloadCarObj * carObj = nil;
    
    //所有此任务的数据存放文件夹
    NSString * tempCarPath = [NSString stringWithFormat:@"%@/%@", _tempCarsPath, sha1string];
    
    //检查以sha1string为名的DownLoadObject在文件夹中是否存在，如果存在则表示上次还没有下载或者解压完成，如果不存在表示需要新建一个下载任务
    NSString * tempCarInfoPath = [NSString stringWithFormat:@"%@/%@_CarInfo", tempCarPath, sha1string];
    
    BOOL isDir;
    if (([[NSFileManager defaultManager] fileExistsAtPath:tempCarInfoPath isDirectory:&isDir] & !isDir)) {
        carObj = [NSKeyedUnarchiver unarchiveObjectWithFile:tempCarInfoPath];
            
        //判断是否已经下载完成了，对于下载完成了的，直接解压
        if(1.0 == carObj.progress)
        {
            carObj.state = Finish_State;
        }
    }
    
    if (carObj == nil) {
        carObj = [[[DownloadCarObj alloc] initWithDownloadObjectType:_downloadObjType] autorelease];
        carObj.tempCarPath = tempCarPath;
        carObj.tempInfoPath = tempCarInfoPath;
        carObj.tempFilePath = [NSString stringWithFormat:@"%@/%@_File.tmp", tempCarPath, sha1string];
        carObj.saveFilePath = (IsVideo == _downloadObjType)? [NSString stringWithFormat:@"%@/%@", carObj.saveAutosPath, fileName] : [NSString stringWithFormat:@"%@/%@_File.zip", tempCarPath, sha1string];
        carObj.progress = 0.0;
        carObj.eTag = @"eTag";
        
        if (!([[NSFileManager defaultManager] fileExistsAtPath:carObj.tempFilePath isDirectory:&isDir] && !isDir))
        {
            if (!([[NSFileManager defaultManager] fileExistsAtPath:carObj.tempCarPath isDirectory:&isDir] && isDir)) {
                NSError * error = nil;
                [[NSFileManager defaultManager] createDirectoryAtPath:carObj.tempCarPath
                                          withIntermediateDirectories:YES
                                                           attributes:nil
                                                                error:&error];
                
            }
            [[NSFileManager defaultManager] createFileAtPath:carObj.tempFilePath contents:[NSData data] attributes:nil];
        }
    }
    
    return carObj;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [iLowLevelNetworkQueue release];
    [iMiddleLevelNetworkQueue release];
    SafeRelease(taskArray);
    [super dealloc];
}

#pragma mark -
- (void)addNotificationWithTask:(NetworkTask*)task{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskFinish:) name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskFinish:) name:NetworkTask_NotificationName_OnFail object:task];
}

- (void)removeNotificationWithTask:(NetworkTask*)task{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
}

- (void)onTaskFinish:(NSNotification*)notification{
    NetworkTask *task = notification.object;
    [self removeNotificationWithTask:task];
    [taskArray removeObject:task];
}

-(void)decompressComplete:(NSNotification *)sender
{
//    DownloadCarObj * object = (DownloadCarObj *)[sender object];
    CarInfo* carInfo = sender.object;
    
    //解压完成后需要删除原来的临时文件
    NSError * error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@", carInfo.downloadCarObj.tempCarPath] error:&error];
    if (nil != error) {
        NSLog(@"decompressComplete:removeItemAtPathError:%@", error);
    }
}

@end
